package com.lanyou.cook.service.security;

import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Root;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lanyou.cook.entity.domain.FieldSystem;
import com.lanyou.cook.entity.domain.SystemInterface;
import com.lanyou.cook.entity.domain.userManagement.User;
import com.lanyou.cook.repository.FieldSystemRepository;
import com.lanyou.cook.repository.userManagement.UserRepository;

/**
 * 当前登录用户相关的业务逻辑层
 * @author 仇伟业
 */
@Service
public class UserSessionService {
	
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private FieldSystemRepository fieldSystemRepository;
	@PersistenceContext
	private EntityManager entityManager;
	
	/**
	 * 获取当前登录用户的帐号名
	 * @return 类型:User 如题
	 */
	public static String getCurrentAuthenticatedUserCode() {
		try {
			Subject subject = SecurityUtils.getSubject();
			if(!subject.isAuthenticated())
				return null;
			PrincipalCollection principalCollection = subject.getPrincipals();
			Object operatorUserCode = principalCollection.asList().get(0);
			if (operatorUserCode != null) {
				return operatorUserCode.toString();
			}
		} catch (Exception ex) {
		}
		return null;
	}
	
	/**
	 * 获取当前登录用户的帐号名
	 * @return 类型:User 如题
	 */
	public static String getCurrentAuthenticatedUserName() {
		try {
			Subject subject = SecurityUtils.getSubject();
			if(!subject.isAuthenticated())
				return null;
			PrincipalCollection principalCollection = subject.getPrincipals();
			Object operatorUserName = principalCollection.asList().get(1);
			if (operatorUserName != null) {
				return operatorUserName.toString();
			}
		} catch (Exception ex) {
		}
		return null;
	}
	
	/**
	 * 获取当前登录用户的实体对象
	 * @return 类型:User 如题
	 */
	public User getCurrentAuthenticatedUser(){
		String userCode = getCurrentAuthenticatedUserCode();
		if(userCode == null)
			return null;
		return userRepository.findByUserCode(userCode);
	}
	
	/**
	 * 获取当前登录用户所管理的领域系统的集合
	 * @return 类型:Collection 如题
	 */
	public Collection<FieldSystem> findFieldSystemsOfCurrentAuthenticatedUserCanManage(){
		String userCode = getCurrentAuthenticatedUserCode();
		if(userCode == null)
			return CollectionUtils.emptyCollection();
		return fieldSystemRepository.findByUsers_UserCode(userCode);
	}
	
	/**
	 * 获取当前登录用户所管理的领域系统的id的集合
	 * @return 类型:Collection 如题
	 */
	public Collection<String> findFieldSystemIdsOfCurrentAuthenticatedUserCanManage(){
		String userCode = getCurrentAuthenticatedUserCode();
		if(userCode == null)
			return CollectionUtils.emptyCollection();
		
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<String> cq = cb.createQuery(String.class).distinct(true);
		
		// 构建FROM和JOIN部分
		Root<User> rootUser = cq.from(User.class);
		Join<SystemInterface, FieldSystem> joinFieldSystem = rootUser.join("fieldSystems");
		
		// 构建WHERE部分
		cq.where(cb.equal(rootUser.get("userCode"), userCode));
		
		// 构建SELECT部分
		cq.select(joinFieldSystem.get("id"));

		// 执行查询
		TypedQuery<String> q = entityManager.createQuery(cq);
		List<String> queryResult = q.getResultList();
		return queryResult;
	}
	
	/**
	 * 获取当前登录用户所管理的领域系统的名称的集合
	 * @return 类型:Collection 如题
	 */
	public Collection<String> findFieldSystemNamesOfCurrentAuthenticatedUserCanManage(){
		String userCode = getCurrentAuthenticatedUserCode();
		if(userCode == null)
			return CollectionUtils.emptyCollection();
		
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<String> cq = cb.createQuery(String.class).distinct(true);
		
		// 构建FROM和JOIN部分
		Root<User> rootUser = cq.from(User.class);
		Join<SystemInterface, FieldSystem> joinFieldSystem = rootUser.join("fieldSystems");
		
		// 构建WHERE部分
		cq.where(cb.equal(rootUser.get("userCode"), userCode));
		
		// 构建SELECT部分
		cq.select(joinFieldSystem.get("name"));

		// 执行查询
		TypedQuery<String> q = entityManager.createQuery(cq);
		List<String> queryResult = q.getResultList();
		return queryResult;
	}
}
